package com.yvon.maple.service.auth.authentication.granter;

import cn.hutool.core.util.StrUtil;
import com.yvon.boot.jwt.model.AuthInfo;
import com.yvon.boot.jwt.utils.TokenUtil;
import com.yvon.boot.redis.service.RedisService;
import com.yvon.maple.service.auth.constant.MessageConstant;
import com.yvon.maple.service.auth.domain.SecurityUser;
import com.yvon.maple.service.auth.param.LoginParam;
import com.yvon.maple.service.auth.service.SecurityUserService;
import com.yvon.maple.service.auth.valicode.validate.code.processor.CodeValidator;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;


/**
 * RefreshTokenGranter
 *
 * @author : Yvon
 * @since : 2021-08-25
 */
@Component(RefreshTokenGranter.GRANT_TYPE)
public class RefreshTokenGranter extends AbstractTokenGranter implements TokenGranter {

    public static final String GRANT_TYPE = "refresh_token";

    public RefreshTokenGranter(TokenUtil tokenUtil, AuthenticationManager authenticationManager, SecurityUserService securityUserService, CodeValidator codeValidator, RedisService redisService) {
        super(tokenUtil, authenticationManager, securityUserService, codeValidator, redisService);
    }

    @Override
    public AuthInfo grant(LoginParam loginParam) {
        String grantType = loginParam.getGrantType();
        String refreshTokenStr = loginParam.getRefreshToken();

        if (StrUtil.isEmpty(grantType) || StrUtil.isEmpty(refreshTokenStr)) {
            throw new BadCredentialsException("加载用户信息失败");
        }

        AuthInfo authInfo = tokenUtil.parseRefreshToken(refreshTokenStr);

        if (!MessageConstant.REFRESH_TOKEN_KEY.equals(authInfo.getTokenType())) {
            throw new BadCredentialsException("refreshToken无效，无法加载用户信息");
        }

        SecurityUser user = (SecurityUser) securityUserService.loadUserByUsername(authInfo.getUsername());

        return createToken(user);

    }
}
